package com.alstudio.ui.module.main;

import java.util.ArrayList;
import java.util.Random;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spannable;
import android.text.TextPaint;
import android.text.style.URLSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alstudio.R;
import com.alstudio.app.LocalEnv;
import com.alstudio.ui.base.TitleAndBottomBarActivity;
import com.alstudio.ui.module.image.browser.ImageViewerActivity;
import com.alstudio.ui.module.setting.MainSettingActivity;
import com.alstudio.utils.ALActivityManager;
import com.alstudio.utils.android.ALSdcardManager;
import com.alstudio.utils.android.imageProcess.ALImageProcessParams;
import com.alstudio.utils.android.imageProcess.ALImageProcessUtils;
import com.alstudio.utils.log.Mylog;
import com.alstudio.view.cropImage.Util;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.dialog.DialogStyle;
import com.alstudio.view.listener.AlItemOnClickListener;
import com.alstudio.view.listener.AlMultiChoiceOnClickListener;
import com.alstudio.view.listener.AlOnClickListener;
import com.alstudio.view.magicimageview.MagicImageViewAttacher;

public class ALStudioActivity extends TitleAndBottomBarActivity {

	private final String TAG = "ALStudioActivity";
	private TextView tv;
	private ImageView img;

	private MagicImageViewAttacher mAttacher;
	
	// private static class MyURLSpan extends ClickableSpan {
	//
	// private String mUrl;
	//
	// MyURLSpan(String url) {
	// mUrl = url;
	// }
	//
	// @Override
	// public void onClick(View widget) {
	// // TODO Auto-generated method stub
	// // Toast.makeText(ctx, “hello!”,Toast.LENGTH_LONG).show();
	// System.out.println("url ----" + mUrl);
	// }
	// }

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleBarContentView(R.layout.main);
		ALActivityManager.getALActivityManager().addActivity(this);
		enableReceiveXmppEvent();
		setupView(this, TAG);
	}

	private void stripUnderlines(TextView textView) {
		Spannable s = (Spannable) textView.getText();
		URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
		for (URLSpan span : spans) {
			int start = s.getSpanStart(span);
			int end = s.getSpanEnd(span);
			s.removeSpan(span);
			span = new URLSpanNoUnderline(span.getURL());
			s.setSpan(span, start, end, 0);
		}
		textView.setText(s);
	}

	private class URLSpanNoUnderline extends URLSpan {
		public URLSpanNoUnderline(String url) {
			super(url);
		}

		@Override
		public void updateDrawState(TextPaint ds) {
			super.updateDrawState(ds);
			ds.setUnderlineText(false);
			ds.setColor(Color.parseColor("#3c92fd"));
		}

	}

	private class MyFragment extends Fragment {
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			Mylog.e("创建fragment");
			return inflater.inflate(R.layout.my_fragment, null);
			// return super.onCreateView(inflater, container,
			// savedInstanceState);
		}
	}

	MyFragment f = null;
	boolean show = true;

	private AnimationSet getAnimation() {
		AnimationSet set = new AnimationSet(true);
		TranslateAnimation up = new TranslateAnimation(0, 0, 0, 0.5f);
		up = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_PARENT, 0,
				TranslateAnimation.RELATIVE_TO_PARENT, 0,
				TranslateAnimation.RELATIVE_TO_PARENT, 0,
				TranslateAnimation.RELATIVE_TO_PARENT, -0.8f);
		up.setDuration(1000);
		TranslateAnimation left = new TranslateAnimation(0, -0.5f, 0, 0);
		left = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_PARENT, 0,
				TranslateAnimation.RELATIVE_TO_PARENT, -0.5f,
				TranslateAnimation.RELATIVE_TO_PARENT, 0,
				TranslateAnimation.RELATIVE_TO_PARENT, 0);
		left.setDuration(2000);
		left.setStartOffset(100);
		TranslateAnimation down = new TranslateAnimation(0, 0.5f, 0, 0);
		down = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_PARENT, 0,
				TranslateAnimation.RELATIVE_TO_PARENT, 0,
				TranslateAnimation.RELATIVE_TO_PARENT, 0,
				TranslateAnimation.RELATIVE_TO_PARENT, 0.8f);
		down.setDuration(1000);
		down.setStartOffset(1000);
		set.addAnimation(up);
		set.addAnimation(left);
		set.addAnimation(down);
		up.setRepeatCount(2);
		left.setRepeatCount(2);
		down.setRepeatCount(2);

		return set;
	}

	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);

		img = (ImageView) findViewById(R.id.egg);

		img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
//				AndroidUtils.toggleAirPlaneMode(ALStudioActivity.this);

//				AndroidUtils.powerOffDevice();
//				AndroidUtils.setRingerMode(ALStudioActivity.this,
//						RingerMode.RINGER_MODE_VIBRATE);

			}
		});
		
		// The MAGIC happens here!
		mAttacher = new MagicImageViewAttacher(img);		
		

		setLeftButtonLable("你妹");
		setCenterTextViewMessage("尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛");
		mDialog = new AlertDialogCreator(this, false,
				DialogStyle.STYLE_TWO_BUTTON_DIALOG_NORMAL, "真的吗 ",
				"尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛尼玛");
		String[] items = {
				"11111111111111111111111111111111111111111111111111111111111111111",
				"2", "2", "2", "2", "2", "2" };
		mDialog = AlertDialogCreator.createOneButtonWithMultiChoiceListDialog(
				this, false, items, new boolean[] { true, false });
		mDialog.setIcon(BitmapFactory.decodeResource(getResources(),
				R.drawable.chat_disturb_off));
		mDialog.setCurrentProgressMessage("10%最大进度100%");

		mDialog.setMultiChoiceClickListener(new AlMultiChoiceOnClickListener() {

			@Override
			public void OnClick(int position, boolean isChecked) {
				// TODO Auto-generated method stub
				System.out.println("~~~~~~" + position + "状态变为###" + isChecked);

			}
		});

		mDialog.setSingleChoiceClickListener(new AlItemOnClickListener() {

			@Override
			public void OnClick(int position) {
				// TODO Auto-generated method stub
				System.out.println("###~~" + position + "被选中###");

			}
		});

		mDialog.setItemClickListener(new AlItemOnClickListener() {

			@Override
			public void OnClick(int position) {
				// TODO Auto-generated method stub
				System.out.println("###" + position + "被选中###");
			}
		});

		mDialog.setTitle("你爹很嚣张");
		mDialog.setLeftKeyListener(new AlOnClickListener() {

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				System.out.println("左边键按下了");
			}
		});

		mDialog.setRightKeyListener(new AlOnClickListener() {

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				System.out.println("右边键按下了");
			}
		});
		mDialog.setCenterKeyListener(new AlOnClickListener() {

			@Override
			public void onClick() {
				// TODO Auto-generated method stub
				System.out.println("中间键按下了");
			}
		});

		setLeftButtonLable("你妹");

		setLeftButtonClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mDialog.showDialog();
				mDialog.setCurrentProgressMessage("10%最大进度100%");

			}
		});

		setRightButtonClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mDialog.updateProgress(10);
				Intent i = new Intent(ALStudioActivity.this,
						MainSettingActivity.class);
				startActivity(i);
			}
		});

		findViewById(R.id.bt_go).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent i = new Intent(ALStudioActivity.this,
						ImageViewerActivity.class);

				if (show) {
					dismissTitleBarNotice();
					dismissBottomBar();
					show = false;
				} else {
					show = true;
					showTitleBarNotice();
					showBottomBar();
				}

				// startActivity(i);
				// System.out.println("aaaaaaaaaaaa");
				// MyToastUtil.dismissToast();

				// overridePendingTransition(R.anim.zoom_enter,
				// R.anim.zoom_exit);
				// GpsUtils.getInstance(ALStudioActivity.this).startGpsModule();
				// VersionManager.getInstance().checkNewVersion("V1.0.0");
				// enabled =
				// AndroidUtils.getAirplaneMode(ALStudioActivity.this);
				// AndroidUtils.toggleAirPlaneMode(ALStudioActivity.this);
				// VersionManager.getInstance().checkNewVersion("V1.0.0");
				// DistributorManager.getInstance().checkDistributor("V1.0.0");
				// AndroidMultiMediaUtils.dispatchTakeVideoIntent(ALStudioActivity.this);
				// FragmentManager fm = getSupportFragmentManager();
				//
				// FragmentTransaction tr = fm.beginTransaction();
				// tr.remove(f);
				// tr.commit();

				// // 截图
				// Intent intent1 = new Intent(ALStudioActivity.this,
				// CropImage.class);
				// intent1.putExtra("aspectX", 1);
				// intent1.putExtra("aspectY", 1);
				// intent1.putExtra("outputX", 640);
				// intent1.putExtra("outputY", 640);
				// intent1.putExtra("return-data", false);
				// String filePath = "/sdcard/1.png";
				// // 存放在头像文件夹
				// File f = new
				// File(Environment.getExternalStorageDirectory().getPath() +
				// "/"
				// + new File(filePath).getName());
				// intent1.putExtra("save_path", f.getPath());
				// intent1.putExtra("image-path", filePath);
				// intent1.putExtra("scale", true);
				//
				// startActivityForResult(intent1,10086);

				ALImageProcessParams param = new ALImageProcessParams();
				// param.setCropRequest(false);
				param.setExplicitCrop(false);
				param.setRequestHeight(1024);
				param.setRequestWidth(1024);
				param.setExplicitCrop(false);

				param.setSavePath(ALSdcardManager.getExtStoragePath()
						+ "/alonso/crops/");
				// selectPhotos(param);
				// showPhotoProcessDialog(param);
				// takePhotos(param);
				// param.setImagePath("/mnt/sdcard/alonso/icons/CROP_20130116_175256_911512514.jpg");
				// cropPhotos(param);
			}
		});
	}

	@Override
	protected void onNoticeItemShow() {
		// TODO Auto-generated method stub
		super.onNoticeItemShow();
		Mylog.e("TOAST显示了");
	}

	@Override
	protected void onNoticeItemdDismiss() {
		// TODO Auto-generated method stub
		super.onNoticeItemdDismiss();
		Mylog.e("TOAST消失了");
	}

	@Override
	protected void onGetProcessPhotosResult(String path, String name) {
		// TODO Auto-generated method stub
		super.onGetProcessPhotosResult(path, name);
		Mylog.e("老子得到路径了: " + path);
		Bitmap bm = BitmapFactory.decodeFile(path);
		// bm = ImageProcessUtils.cropImage(bm,48,48);
		bm = Util.extractMiniThumb(bm, 80, 80);
		bm = ALImageProcessUtils.getRoundCornerBitmap(bm, 10);
		img.setImageBitmap(bm);
	}

	@Override
	public void handleLoginedEvent() {
		// TODO Auto-generated method stub
		Mylog.e("+++++++++handleLoginedEvent++++++++++");
		Toast.makeText(ALStudioActivity.this, "登录成功了", Toast.LENGTH_LONG)
				.show();
		LocalEnv.mUIEventHandler.onUILoginRequestEvent("", "");

	}

	@Override
	public void handleLogoutEvent() {
		// TODO Auto-generated method stub
		Mylog.e("+++++++++handleLogoutEvent++++++++++");

	}

	@Override
	public void handlerOnConflictEvent() {
		// TODO Auto-generated method stub
		Mylog.e("+++++++++handlerOnConflictEvent++++++++++");

	}

	@Override
	public void handlerOnNewMessageArrivedEvent() {
		// TODO Auto-generated method stub

	}

	@Override
	public void handlerOnMessageReceipt() {
		// TODO Auto-generated method stub

	}

	/**
	 * get the image by the given key
	 */
	private ImageGetter imageGetter = new Html.ImageGetter() {
		@Override
		public Drawable getDrawable(String source) {
			Drawable drawable = null;
			String sourceName = ALStudioActivity.this.getPackageName()
					+ ":drawable/" + source;
			int id = ALStudioActivity.this.getResources().getIdentifier(
					sourceName, null, null);
			if (id != 0) {
				drawable = ALStudioActivity.this.getResources().getDrawable(id);
				if (drawable != null) {
					drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
							drawable.getIntrinsicHeight());
				}
			}
			return drawable;
		}
	};

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	private void showExtraAnimation(int count) {
		ImageView v = null;
		for (int i = 0; i < count; i++) {
			v = new ImageView(this);
			v.setImageResource(R.drawable.flash_14);
			addContentView(v, getLayoutParams());
		}
	}

	private FrameLayout.LayoutParams getLayoutParams() {

		FrameLayout.LayoutParams p = new FrameLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

		Random random = new Random();// 指定种子数字

		int leftOrRight = random.nextInt(5);
		boolean center = false;
		switch (leftOrRight) {
		case 0:
			p.gravity = Gravity.LEFT;
			p.bottomMargin = random.nextInt(50) + 10;
			break;
		case 1:
			p.gravity = Gravity.CENTER_HORIZONTAL;
			break;
		case 2:
			p.gravity = Gravity.RIGHT;
			break;
		case 3:
			p.gravity = Gravity.CENTER;
			center = true;
			break;
		case 4:
			p.gravity |= Gravity.BOTTOM;
			break;
		}

		if (!center) {
			if (random.nextBoolean()) {
				p.gravity |= Gravity.BOTTOM;
			}
		}

		p.bottomMargin = getFestevalRandom();
		p.topMargin = getFestevalRandom();
		p.leftMargin = getFestevalRandom();
		p.rightMargin = getFestevalRandom();
		return p;
	}
	
	private ArrayList<Integer> list = new ArrayList<Integer>();

	private int getFestevalRandom() {

		final Random rm = new Random();
		int m = rm.nextInt(100) + 100;
		int offset = rm.nextInt(50) + m;
		for (int i = 0; i < 10; i++) {
			if (!list.contains(offset)) {
				list.add(offset);
				break;
			}
			m = rm.nextInt(100);
			offset = rm.nextInt(i + 50) + m;
		}

		return offset;
	}
	
	@Override
	public void onDataConnectionLost() {
		// TODO Auto-generated method stub
		super.onDataConnectionLost();
		Mylog.e("连接已丢失");
	}

}